var express = require("express");
var router = express.Router();
let Dec = require("decimal.js");

const task = require("../model/task");
const completeTask = require("../model/completeTask");
const user_login = require("../model/user_login");

router.post("/api/v1/Task_completeTask", async function(req, res) {
  try {
    var { TaskIndex, userid } = req.body;
    //任务信息
    var taskdata = await task.findOne({ index: TaskIndex }).exec();
    //用户信息
    var userdata = await user_login.findById({ _id: userid }).exec();

    console.log(taskdata);
    console.log(userdata);

    let startTime = new Date(
      new Date(new Date().getTime()).setHours(0, 0, 0, 0)
    ); // 当天0点
    let endTime = new Date(
      new Date(new Date().getTime()).setHours(23, 59, 59, 999)
    );
    console.log(startTime);

    console.log(endTime);
    var ALLcompleteTaskdata = await completeTask
      .find({
        userid: userid,
        $and: [
          { complete_time: { $gt: startTime } },
          { complete_time: { $lt: endTime } }
        ]
      })
      .exec();
    console.log("completeTaskdata", ALLcompleteTaskdata);
    var todayintegral = 0;
    for (let index = 0; index < ALLcompleteTaskdata.length; index++) {
      const element = ALLcompleteTaskdata[index];
      todayintegral = Dec(element.integral)
      .add(new Dec(todayintegral))
      .toNumber();
    }
    console.log('todayintegral--今天的积分',todayintegral)
    if (todayintegral >= 35) {
      res.json({
        code: 201,
        text: "当日获取积分已达上限"
      });
    }else{
    var completeTaskdata = await completeTask
      .find({
        taskid: taskdata._id,
        userid: userid,
        $and: [
          { complete_time: { $gt: startTime } },
          { complete_time: { $lt: endTime } }
        ]
      })
      .exec();
    console.log("completeTaskdata", completeTaskdata);
    //当日该任务完成数是否达标
    if (parseInt(completeTaskdata.length) < parseInt(taskdata.frequency)) {
      //计算兑换后 用户剩余多少积分
      var lastInt = Dec(taskdata.integral)
        .add(new Dec(userdata.integral))
        .toNumber();
      console.log(lastInt, "计算后积分");
      user_login.findByIdAndUpdate(
        { _id: userid },
        {
          $set: {
            integral: lastInt
          }
        },
        function(err) {
          if (err) {
            res.send(err);
            return;
          }
        }
      );
      var newcompleteTaskdata = {
        taskid: taskdata._id, //任务id
        userid: userid, //用户id
        inttype: "add", //积分变动类型
        complete_time: new Date(), //完成时间
        integral: taskdata.integral, //变动积分
        taskPoints: taskdata.integral //任务原有积分
      };

      completeTask.create(newcompleteTaskdata);
      res.json({
        code: 200,
        text: taskdata.taskname + "任务完成,积分+" + taskdata.integral
      });
    } else {
      res.json({
        code: 201,
        text: "当日任务已达上限"
      });
    }
    console.log(completeTaskdata);
   }


  } catch (error) {
    res.status(500).send(error);
  }
});

// 导出模块（在 app.js 中引入）
module.exports = router;
